import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 获取充值记录列表
const fetchRechargeRecords = async (params) => {
  return request('/api/v1/recharge/record', {
    method: 'GET',
    params,
  });
};

// 获取充值记录详情
const fetchRechargeDetail = async (id) => {
  return request(`/api/v1/recharge/record/${id}`, {
    method: 'GET',
  });
};

// 获取会员信息
const fetchMemberDetail = async (id) => {
  return request(`/api/v1/member/${id}`, {
    method: 'GET',
  });
};

// 获取套餐信息
const fetchPackageDetail = async (id) => {
  return request(`/api/v1/recharge/package/${id}`, {
    method: 'GET',
  });
};

const RechargeRecord = () => {
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [memberMap, setMemberMap] = useState({});
  const [packageMap, setPackageMap] = useState({});

  // 获取充值记录列表
  const fetchRecordList = async () => {
    try {
      setLoading(true);
      const res = await fetchRechargeRecords({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        const list = res.data.list || [];
        setRecords(list);
        
        // 获取会员信息和套餐信息
        await fetchMembersAndPackages(list);
      } else {
        message.error(res.message || '获取充值记录失败');
      }
    } catch (error) {
      console.error('获取充值记录出错:', error);
      message.error('获取充值记录失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 获取会员和套餐信息
  const fetchMembersAndPackages = async (records) => {
    try {
      const memberIds = new Set();
      const packageIds = new Set();
      
      // 收集所有需要获取的会员ID和套餐ID
      records.forEach(record => {
        if (record.member_id && !memberMap[record.member_id]) {
          memberIds.add(record.member_id);
        }
        if (record.package_id && !packageMap[record.package_id]) {
          packageIds.add(record.package_id);
        }
      });
      
      // 获取会员信息
      const memberPromises = Array.from(memberIds).map(async (id) => {
        try {
          const res = await fetchMemberDetail(id);
          if (res.success && res.data) {
            return { id, data: res.data };
          }
          return null;
        } catch (error) {
          console.error(`获取会员信息出错 ID: ${id}`, error);
          return null;
        }
      });
      
      // 获取套餐信息
      const packagePromises = Array.from(packageIds).map(async (id) => {
        try {
          const res = await fetchPackageDetail(id);
          if (res.success && res.data) {
            return { id, data: res.data };
          }
          return null;
        } catch (error) {
          console.error(`获取套餐信息出错 ID: ${id}`, error);
          return null;
        }
      });
      
      // 等待所有请求完成
      const memberResults = await Promise.all(memberPromises);
      const packageResults = await Promise.all(packagePromises);
      
      // 更新会员和套餐映射
      const newMemberMap = { ...memberMap };
      const newPackageMap = { ...packageMap };
      
      memberResults.forEach(result => {
        if (result) {
          newMemberMap[result.id] = result.data;
        }
      });
      
      packageResults.forEach(result => {
        if (result) {
          newPackageMap[result.id] = result.data;
        }
      });
      
      setMemberMap(newMemberMap);
      setPackageMap(newPackageMap);
    } catch (error) {
      console.error('获取会员和套餐信息出错:', error);
    }
  };

  useEffect(() => {
    fetchRecordList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看充值详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchRechargeDetail(record.id);
      if (res.success) {
        const detailData = res.data;
        
        // 如果详情中的会员ID或套餐ID不在缓存中，则获取相应信息
        if (detailData.member_id && !memberMap[detailData.member_id]) {
          try {
            const memberRes = await fetchMemberDetail(detailData.member_id);
            if (memberRes.success && memberRes.data) {
              setMemberMap(prev => ({
                ...prev,
                [detailData.member_id]: memberRes.data
              }));
            }
          } catch (error) {
            console.error(`获取会员信息出错 ID: ${detailData.member_id}`, error);
          }
        }
        
        if (detailData.package_id && !packageMap[detailData.package_id]) {
          try {
            const packageRes = await fetchPackageDetail(detailData.package_id);
            if (packageRes.success && packageRes.data) {
              setPackageMap(prev => ({
                ...prev,
                [detailData.package_id]: packageRes.data
              }));
            }
          } catch (error) {
            console.error(`获取套餐信息出错 ID: ${detailData.package_id}`, error);
          }
        }
        
        setCurrentRecord(detailData);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取充值详情失败');
      }
    } catch (error) {
      console.error('获取充值详情出错:', error);
      message.error('获取充值详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '充值单号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 180,
    },
    {
      title: '用户',
      dataIndex: 'member_id',
      key: 'member_id',
      width: 120,
      render: (member_id) => {
        const member = memberMap[member_id];
        return member ? member.name || member.phone || member_id : member_id;
      },
    },
    {
      title: '充值金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (text) => `¥${text.toFixed(2)}`,
    },
    {
      title: '赠送金额',
      dataIndex: 'gift_amount',
      key: 'gift_amount',
      width: 120,
      render: (text) => (text !== null && text !== undefined) ? `¥${text.toFixed(2)}` : '¥0.00',
    },
    {
      title: '套餐名称',
      dataIndex: 'package_id',
      key: 'package_id',
      width: 150,
      render: (package_id) => {
        const packageInfo = packageMap[package_id];
        return packageInfo ? packageInfo.name || package_id : package_id;
      },
    },
    {
      title: '支付方式',
      dataIndex: 'payment_channel',
      key: 'payment_channel',
      width: 120,
      render: (method) => {
        const methodMap = {
          'wechat': '微信支付',
          'alipay': '支付宝',
          'unionpay': '银联支付',
          'balance': '余额支付',
        };
        return methodMap[method] || method;
      },
    },
    {
      title: '充值状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 2:
            color = 'green';
            text = '成功';
            break;
          case 1:
            color = 'gold';
            text = '处理中';
            break;
          case 0:
            color = 'red';
            text = '失败';
            break;
          default:
            color = 'default';
            text = status;
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '充值时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render:(value)=>moment(value*1000).format("YYYY-MM-DD mm:hh:ss"),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="link" 
          icon={<EyeOutlined />} 
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.order_no) {
      params.order_no = values.order_no;
    }
    if (values.member_id) {
      params.member_id = values.member_id;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.payment_channel) {
      params.payment_channel = values.payment_channel;
    }
    if (values.dateRange && values.dateRange.length === 2) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="order_no" label="充值单号">
            <Input placeholder="请输入充值单号" allowClear />
          </Form.Item>
          <Form.Item name="member_id" label="用户名">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item name="payment_channel" label="支付方式">
            <Select placeholder="请选择支付方式" style={{ width: 150 }} allowClear>
              <Option value="wechat">微信支付</Option>
              <Option value="alipay">支付宝</Option>
              <Option value="unionpay">银联支付</Option>
              <Option value="balance">余额支付</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="充值状态">
            <Select placeholder="请选择充值状态" style={{ width: 150 }} allowClear>
              <Option value={2}>成功</Option>
              <Option value={1}>处理中</Option>
              <Option value={0}>失败</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="充值时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={records}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />

        {/* 充值详情弹窗 */}
        <Modal
          title="充值详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={[
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>,
          ]}
          width={700}
        >
          {currentRecord && (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="充值单号">{currentRecord.order_no}</Descriptions.Item>
              <Descriptions.Item label="用户名">
                {memberMap[currentRecord.member_id] 
                  ? (memberMap[currentRecord.member_id].name || memberMap[currentRecord.member_id].phone || currentRecord.member_id) 
                  : currentRecord.member_id}
              </Descriptions.Item>
              <Descriptions.Item label="充值金额">¥{currentRecord.amount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="赠送金额">¥{currentRecord.gift_amount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="套餐名称">
                {packageMap[currentRecord.package_id] 
                  ? (packageMap[currentRecord.package_id].name || currentRecord.package_id) 
                  : currentRecord.package_id}
              </Descriptions.Item>
              <Descriptions.Item label="支付方式">
                {{
                  'wechat': '微信支付',
                  'alipay': '支付宝',
                  'unionpay': '银联支付',
                  'balance': '余额支付',
                }[currentRecord.payment_channel] || currentRecord.payment_channel}
              </Descriptions.Item>
              <Descriptions.Item label="充值状态">
                <Tag color={
                  currentRecord.status === 2 ? 'green' :
                  currentRecord.status === 1 ? 'gold' :
                  currentRecord.status === 0 ? 'red' : 'default'
                }>
                  {{
                    2: '成功',
                    1: '处理中',
                    0: '失败',
                  }[currentRecord.status] || currentRecord.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="充值时间">{moment(currentRecord.created_at*1000).format("YYYY-MM-DD mm:hh:ss")}</Descriptions.Item>
              <Descriptions.Item label="交易单号">{currentRecord.transactionNo || '-'}</Descriptions.Item>
              <Descriptions.Item label="操作人">{currentRecord.operatorName || '-'}</Descriptions.Item>
              <Descriptions.Item label="备注" span={2}>{currentRecord.remark || '-'}</Descriptions.Item>
            </Descriptions>
          )}
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default RechargeRecord;